package im.yisme.view.activities;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import im.yisme.R;
import im.yisme.controler.service.CtrlServiceProvider;
import im.yisme.controler.service.MusicCtrlService;
import im.yisme.model.service.ModelServiceProvider;
import im.yisme.model.service.MusicRepositoryService;
import im.yisme.view.service.ViewService;
import im.yisme.view.service.ViewServiceProvider;
import im.yisme.view.ui.MainView;
import im.yisme.view.ui.animation.BGP;
import im.yisme.view.ui.animation.MusicLibAnimationSet;
import im.yisme.view.ui.util.MusicLibAdapter;
import im.yisme.vo.MusicVO;
import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MusicLibraryActivity extends Rotate3DActivity {
	private ViewService viewCtrl;
	private MusicCtrlService ctrl;
	private MusicRepositoryService model;
	private InputMethodManager imm;
	
	//-------------------------------
	//音乐库界面组件
	private ViewGroup musicLib;
	private ListView list;
	private int selectedItem;
	private ViewGroup detailPane;
	private TextView artistText,musicNameText,durationText;
	private ImageButton modifyButton,importButton,backButton;
	private ImageView title;
	//修改界面组件
	private ViewGroup modifyPane;
	private EditText musicNameEdit,artistEdit;
	private ImageButton sureButton,cancelButton;
	//
	private MainView mainView;
	//-------------------------------
	
	//-------------------------------
	//动画
	private MusicLibAnimationSet animationSet;
	private Handler bgpHandler;
	private BGP bgp; 
	//-------------------------------
	
	//-------------------------------
	//音乐文件数据
	private ArrayList<MusicVO> musicVOList;
	private MusicVO newAddMusicVO;
	//-------------------------------
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_musiclib);
		
		viewCtrl=ViewServiceProvider.getViewService();
		ctrl = CtrlServiceProvider.getMusicCtrlService();
		model = ModelServiceProvider.getMusicRepositoryService();
		
        init();
		
		
		
		
		
	}
	
	private void jumpToMain(){
		Intent intent = new Intent(this,MainActivity.class);
		viewCtrl.jumpTo(intent);
	}
	private void jumpToImport(){
		Intent intent = new Intent(this,ImportMusicActivity.class);
		startActivityForResult(intent, 0);
	}
	protected void onResume(){
		super.onResume();
		viewCtrl.updateTopActivity(this);
		
		
	}
	protected void onRestart(){
		super.onRestart();
		bgp = new BGP(bgpHandler);
		bgp.start();
	}
	protected void onStop(){
		super.onStop();
		bgp.stopRunning();
		if(mainView != null) mainView.stop();
	}
	
	public void deleteMusic(int position){
		ctrl.removeMusicFromRepository(musicVOList.get(position));
		initList();
	}
	
	private void init(){
		
		musicLib = (RelativeLayout) findViewById(R.id.musiclib);
		imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		
		initDetailPane();
		initList();
		initButtons();
		initTitle();
		initAnimation();
		
		
	}
	private void initAnimation() {
		// TODO Auto-generated method stub
		animationSet = new MusicLibAnimationSet(this, this, list, detailPane, importButton, backButton, title);
		
		bgpHandler = new Handler(){
			public void handleMessage(Message m){
				switch (m.what) {
				case 0:
					musicLib.setBackgroundResource(R.drawable.bgp1);
					break;
				case 1:
					musicLib.setBackgroundResource(R.drawable.bgp2);
					break;
				case 2:
					musicLib.setBackgroundResource(R.drawable.bgp3);
					break;
				case 3:
					musicLib.setBackgroundResource(R.drawable.bgp4);
					break;
				default:
					break;
				}
				
			}
		};
		bgp = new BGP(bgpHandler);
		bgp.start();
		
		
	
	}

	private void initList(){
		list = (ListView) findViewById(R.id.listView_musicLib);
		
		
		Iterator<MusicVO> it = model.getMusicList();
		ArrayList<Map<String, Object>> data = new ArrayList<Map<String,Object>>();
		musicVOList = new ArrayList<MusicVO>();
		
		while (it.hasNext()) {
			MusicVO musicVO = it.next();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("name", musicVO.getName()+" - "+musicVO.getArtist());
			data.add(map);
			musicVOList.add(musicVO);
		}
				
		
		MusicLibAdapter adapter = new MusicLibAdapter(this, this, data);
		
		list.setAdapter(adapter);
		
		selectedItem = 0;
		updateDetailPaneInfo();
		
		list.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, final int arg2,
					long arg3) {
				// TODO Auto-generated method stub				
							
				if(arg2 != selectedItem){
				    detailPane.startAnimation(animationSet.detailPaneZoomOut);

				    selectedItem = arg2;
				}
			}
		});
		
	}
	
	private void initButtons(){
		
		modifyButton = (ImageButton) findViewById(R.id.imageButton_modify);
		importButton = (ImageButton) findViewById(R.id.imageButton_import);
		backButton = (ImageButton) findViewById(R.id.imageButton_back);
		
		modifyButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				detailPane.startAnimation(animationSet.detailPaneRightOut);
				list.startAnimation(animationSet.listLeftOut);
				importButton.startAnimation(animationSet.importButtonBottomOut);
				backButton.startAnimation(animationSet.backButtonBottomOut);
				title.startAnimation(animationSet.titleFadeOut);
				
				initModify(musicNameText.getText(),artistText.getText());
				modifyPane.startAnimation(animationSet.modifyPaneTopIn);
			}
		});
		
		importButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				jumpToImport();
			}
		});
		backButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				musicLib.startAnimation(lOutAnimation);
				mainView = new MainView(MusicLibraryActivity.this);
				setContentView(mainView);
				mainView.startAnimation(rInAnimation);		
				rInAnimation.setAnimationListener(new AnimationListener() {
					
					public void onAnimationStart(Animation animation) {}	
					public void onAnimationRepeat(Animation animation) {}
					
					public void onAnimationEnd(Animation animation) {
						// TODO Auto-generated method stub
						back();
					}
				});
			}
		});
	}
	private void initDetailPane(){
		detailPane = (RelativeLayout) findViewById(R.id.relativeLayout_detailPane);
		artistText = (TextView) findViewById(R.id.textView_artist);
		musicNameText = (TextView) findViewById(R.id.textView_musicName);
		durationText = (TextView) findViewById(R.id.textView_duration);
	}
	private void initTitle(){
		title = (ImageView) findViewById(R.id.imageView_title);
	}
	private void initModify(CharSequence musicName,CharSequence artist){
	
		modifyPane = (ViewGroup) findViewById(R.id.relativeLayout_modify);
		musicNameEdit = (EditText) findViewById(R.id.editText_musicName);
		musicNameEdit.setText(musicName);
		artistEdit = (EditText) findViewById(R.id.editText_artist);
		artistEdit.setText(artist);
		sureButton = (ImageButton) findViewById(R.id.imageButton_sure);
		sureButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				modifyPackUp();
				MusicVO musicVO = musicVOList.get(selectedItem);
				musicVO.setName(musicNameEdit.getText().toString());
				musicVO.setArtist(artistEdit.getText().toString());
				ctrl.alterMusicInfo(musicVO);
				initList();
			}
		});
		cancelButton = (ImageButton) findViewById(R.id.imageButton_cancel);
		cancelButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				modifyPackUp();			
			}
		});
		animationSet.registerModifyPane(modifyPane);
		
	}
	private void modifyPackUp(){
		modifyPane.startAnimation(animationSet.modifyPaneTopOut);
		
		detailPane.startAnimation(animationSet.detailPaneRightIn);
		list.startAnimation(animationSet.listLeftIn);
		importButton.startAnimation(animationSet.importButtonBottomIn);
		backButton.startAnimation(animationSet.backButtonBottomIn);
		title.startAnimation(animationSet.titleFadeIn);
	}
	public void updateDetailPaneInfo(){
		if(musicVOList.size() == 0) return;																																																																					
		MusicVO musicVO = musicVOList.get(selectedItem);
		musicNameText.setText(musicVO.getName());
		artistText.setText(musicVO.getArtist());
		durationText.setText(musicVO.getDuration());
	}
	private void back(){
		jumpToMain();
		overridePendingTransition(0, 0);
	}
	
	public void onBackPressed(){}
	public boolean onTouchEvent(MotionEvent event) {  
        // TODO Auto-generated method stub  
        if (event.getAction() == MotionEvent.ACTION_DOWN) {  
            if (this.getCurrentFocus() != null) {  
                if (this.getCurrentFocus().getWindowToken() != null) {  
                    imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),  
                            InputMethodManager.HIDE_NOT_ALWAYS);  
                }  
            }  
        }  
        return super.onTouchEvent(event);  
    }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(resultCode == RESULT_OK){
			String filePath = data.getStringExtra("file");
			String temp[] = filePath.split("\\/");
			String musicName = temp[temp.length-1].split("\\.")[0];
		    String artist = "";
			String name = "";
			
			if(musicName.contains("-")){
				name = musicName.split("-")[0];
				artist = musicName.split("-")[1];
			}
			else {
				name = musicName;
			}
			
			newAddMusicVO = new MusicVO(0, artist, name, "0:00");
			newAddMusicVO.setFilePath(filePath);
			
			MediaPlayer player = MediaPlayer.create(getApplicationContext(), Uri.parse(filePath));
			player.setOnPreparedListener(new OnPreparedListener() {
				
				public void onPrepared(MediaPlayer mp) {
					// TODO Auto-generated method stub
					String minute = (mp.getDuration()/60000)+"";
					String seconds = (mp.getDuration()%60000/1000)+"";
					while(seconds.length() < 2)
						seconds = "0" + seconds;					
					
					newAddMusicVO.setDuration(minute+":"+seconds);		
					ctrl.addMusicToRepository(newAddMusicVO);
					initList();
					mp.release();
				}
			});
			try {
				 if (player != null) {
					 player.stop();
			        }
				player.prepare();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	
}
